using System;
using System.Threading;

public static class Program {
   public static void Main() {
      Singleton s = Singleton.Value;
   }
}

public sealed class Singleton {
   // s_lock is required for thread safety and having this object
   // assumes that creating the singleton object is more expensive 
   // than creating a System.Object object and that creating the 
   // singleton object may not be necessary at all. Otherwise, 
   // it is more efficient and easier to just create the singleton object 
   // in a class constructor
   private static Object s_lock = new Object();

   // Volatile is required for the ECMA memory model
   // Volatile is not required for the CLR memory model
   private static /* volatile */ Singleton s_value; 
   
   // Private constructor prevents any code outside
   // this class form creating an instance
   private Singleton() {}

   // Public, static property that returns the 
   // singleton object (creating it if necessary)
   public static Singleton Value {
      get {
         // Has the singleton object already been created?
         if (s_value == null) {
            // No, only one thread should create it
            lock (s_lock) {
               // Did another thread created it?
               if (s_value == null) {
                  // No, OK, this thread will create it.

                  // Volatile ensures that all of singleton object's fields 
                  // (initialied by the constructor) are flushed before
                  // other threads see the reference to the Singleton object
                  s_value = new Singleton();
               }
            }
         }

         // Return a reference to the single object
         return s_value;
      }
   }
}


namespace SimplifiedSingleton {
   public sealed class Singleton {
      private static Singleton s_value = new Singleton();

      // Private constructor prevents any code outside
      // this class form creating an instance
      private Singleton() { }

      // Public, static property that returns the singleton object
      public static Singleton Value {
         get {
            // Return a reference to the single object
            return s_value;
         }
      }
   }
}